package com.myk.game.gobangchess;

import com.myk.game.gobangchess.constants.Msger;
import com.myk.game.gobangchess.utils.DateTimeUtil;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.concurrent.*;

/**
 * 机器人 玩家
 */
public class RobotPlayer extends Player {

    private final ThreadPoolExecutor executor;
    private final Runnable onAiCallback;

    //真人玩家id长度小于8，昵称也不能有特殊符号，机器人的账户信息要和真人的不一样。
    public RobotPlayer(Room room, String idCode, String nickName, Runnable onAiCallback) {
        super(null, null, null, null, new Account(idCode, nickName, DateTimeUtil.localDateTimeToStr(LocalDateTime.now(), DateTimeUtil.DATE_FORMAT)));
        setEnteringRoom(room);
        this.onAiCallback = onAiCallback;
        // 使用自定义策略
        this.executor = new ThreadPoolExecutor(
                1,
                1,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(), // 无界队列
                (r, executor) -> {
                    // 清空队列中的所有任务
                    executor.getQueue().clear();
                    // 提交新任务
                    executor.submit(onAiCallback);
                }
        );
    }

    @Override
    public void run() {
        if (onAiCallback != null) {
            onAiCallback.run();
        }
    }

    @Override
    public void recycle() {

    }

    @Override
    public void sendMessage(String type, String value) {
        if (type.equals(Msger.youCanMove)) {
            if (getEnteringRoom() != null && getEnteringRoom().gameTip.equals("-1")) {
                getEnteringRoom().gameTip = getNickNameOrTemp() + "正在思考中...";
            }
            //回调ai执行
            executor.submit(onAiCallback);
        }
        else if (type.equals(Msger.youNotMove)){
            if (getEnteringRoom() != null && getEnteringRoom().gameTip.equals(getNickNameOrTemp() + "正在思考中...")) {
                getEnteringRoom().gameTip = "-1";
            }
        }
    }

    @Override
    public void updateLoginTime() {

    }

    @Override
    public void updatePlayingInfo(Room room, Player opponent,boolean isWin) {

    }

    @Override
    public String getPlayerInfo() {
        return "机器人没有保存玩家信息";
    }

    @Override
    public void onLoginSuccess() {

    }

    @Override
    public void reConnect(Socket socket, DataOutputStream dos, DataInputStream dis, Account account) {

    }

}
